package com.sun.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.entities.Emp;
import com.sun.mapper.EmpMapper;
import com.sun.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author hugh.sun
 * @date 2021/11/15 0:45
 */
@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Resource
    private EmpMapper empMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void add(Emp emp) {
        empMapper.insert(emp);
    }

    @Override
    public Object getEmpById(Integer id) {
        //1.如果reids中有这个数据那么在redis中取值，如果redis中没有这个数据那么在数据库中查询出来之后放到redis中去，
        //然后用的时候再从redis中取值。添加双重验证
        String key = "user:"+id;
        Object userObj =  redisTemplate.opsForValue().get(key);
        if (userObj == null) {
            synchronized (this.getClass()){
                userObj =  redisTemplate.opsForValue().get(key);
                    if(userObj == null){
                        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>在数据库中查询");
                        Emp emp1 = empMapper.selectByPrimaryKey(id);
                        redisTemplate.opsForValue().set(key, emp1);
                        return emp1;
                    }else {
                        log.debug(">>>>>>>>>>>>>>>>>（同步）>>>>>>>>>>>>>>在redis中查询");
                    }
            }
        } else {
            log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>在redis中查询");
        }
        return userObj;

    }

    @Override
    public PageInfo selectUserByname(Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        List<Emp> emps = empMapper.selectUsersByName(null);

        return new PageInfo(emps);

    }

}
